﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;

namespace SystemX.WebControls
{
	/// <summary>
	/// common draw donw selector
	/// </summary>
	public class SiteDDSelect:WebControl
	{
		public string Name { get; set; }
		public string Tip { get; set; }
		public string KeyField { get; set; }
		public string DescField { get; set; }
		public IEnumerable<object> DataSource { get; set; }
        private StringBuilder htmlSb;

		protected override void Render(System.Web.UI.HtmlTextWriter writer)
		{
			writer.Write(OuterHtml);
		}
		const string HeaderTemplate = "<select id=\"{0}\" name=\"{1}\"><option value=\"\" selected=\"selected\">{2}</option>";
		const string OptionTemplate = "<option value=\"{0}\">{1}</option>";
		const string FooterTemplate = "</select>";

        void prepareHtml() {
            if (htmlSb.Length > 0) return;

            htmlSb = new StringBuilder();
            htmlSb.AppendFormat(HeaderTemplate, ID, Name, Tip ?? "Please select one item.");
            if (DataSource != null && DataSource.Count() > 0)
            {

                DataSource.ToList().ForEach(x =>
                {
                    if (KeyField == null)
                    {
                        htmlSb.AppendFormat(OptionTemplate, x, x);
                    }
                    else
                    {
                        htmlSb.AppendFormat(OptionTemplate, x.GetPropertyValue(KeyField), x.GetPropertyValue(DescField));
                    }
                });
            }
            htmlSb.Append(FooterTemplate); 
        }

        public string OuterHtml {
            get
            {
                prepareHtml();
                return htmlSb.ToString();
            }
        }
	}
}
